<template>
  <div class="tooltip-box" ref="tooltipBoxRef" :style="`width: ${maxWidth}`">
    <span
      v-if="tooltipBoxWidth && !tooltipBoxContentWidth && content"
      class="tooltip-box__content"
      style="opacity: 0"
      ref="tooltipBoxContentRef"
    >
      <slot>{{ content }}</slot>
    </span>

    <component
      v-if="tooltipBoxWidth || isMounted"
      :is="tooltipBoxWidth <= tooltipBoxContentWidth ? ElTooltip : 'div'"
      effect="dark"
      placement="top"
    >
      <template #content>
        <div :style="`max-width: ${maxWidth}`">
          {{ content }}
        </div>
      </template>
      <span
        v-if="content"
        class="tooltip-box__content"
        :style="`max-width: ${maxWidth}`"
      >
        <slot>{{ content }}</slot>
      </span>
      <span v-else>--</span>
    </component>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElTooltip } from 'element-plus'
import { tooltipBoxProps } from './tooltipBox'
import { isNumber } from '@/utils'

defineOptions({
  name: 'MTooltipBox'
})

const props = defineProps(tooltipBoxProps)

const tooltipBoxWidth = ref(0)
const tooltipBoxRef = ref<HTMLDivElement>()

const tooltipBoxContentWidth = ref(0)
const tooltipBoxContentRef = ref<HTMLDivElement>()

const maxWidth = computed(() => {
  const width = props.width
  if (!width) {
    return tooltipBoxWidth.value ? `${tooltipBoxWidth.value}px` : '100%'
  }
  return isNumber(width) ? `${width}px` : width
})

const isMounted = ref(false)
onMounted(() => {
  tooltipBoxWidth.value = tooltipBoxRef.value?.offsetWidth || 0
  nextTick(() => {
    tooltipBoxContentWidth.value = tooltipBoxContentRef.value?.offsetWidth || 0
    isMounted.value = true
  })
})
</script>

<style lang="scss" scoped>
.tooltip-box {
  display: inline-block;
  width: 100%;
}
.tooltip-box__content {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
